<?php

namespace App\Http\Middleware;

//use App\Models\VueAdmin as Admin;
use App\Exceptions\ParameterException;

use Closure;

class Permission
{
    const CODE_AUTHFAIL = 401;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('token');
        if (!$token) {
            $token = $request->input('token'); // 调试用
        }
        if (!$token) {
            throw new ParameterException([
                'code' => self::CODE_AUTHFAIL,
                'msg' => 'token 不能为空！'
            ]);
        }
        $jwt_data = \App\Services\AuthToken::verify($token);
        if (!$jwt_data || !$jwt_data->admin_id) {
            throw new ParameterException([
                'code' => self::CODE_AUTHFAIL,
                'msg' => '登录状态已过期！',
            ]);
        }
        $admin = cache('auth_admin_id-' . $jwt_data->admin_id);
        if (!$admin) {
            throw new ParameterException([
                'code' => self::CODE_AUTHFAIL,
                'msg' => 'token值已过期，请重新登录！'
            ]);
        }

        return $next($request);
    }
}
